#include "threadPool.h"
#include "config.h"

int main(int argc, char* argv[]) {
    // ./server
    if(argc > 2) {
        fprintf(stderr, "ERROR: Invalid arguments.\n");
        exit(1);
    }
    // 读取配置文件
    config_t configs[50];
    bzero(configs, sizeof(configs));
    int config_count;
    if(argc == 2) {
        read_conf(argv[1], configs, &config_count);
    } else {
        read_conf("../conf/server.conf", configs, &config_count);
    }

    char ip[CONFIG_LEN] = {0};
    char port[CONFIG_LEN] = {0};
    char workerNum[CONFIG_LEN] = {0};

    get_conf_value(configs, config_count, "ip", ip);
    get_conf_value(configs, config_count, "port", port);
    get_conf_value(configs, config_count, "workerNum", workerNum);

    printf("===== SERVER RUN ========\n");
    printf("===== IP = %s ======\n",ip);
    printf("===== PORT = %s =======\n",port);
    printf("===== WORKERNUM = %s =====\n",workerNum);
    printf("\n");

    threadPool_t threadPool;
    initThreadPool(atoi(workerNum), &threadPool);
    makeWorker(&threadPool);
    int sockfd;
    tcpInit(ip, port, &sockfd);

    free_configs(configs, config_count);
    int epfd = epoll_create(1);
    epollAdd(epfd, sockfd);

    struct epoll_event readyset[10];
    while(1) {
        int readynum = epoll_wait(epfd, readyset, 10, -1);
        for(int i = 0; i < readynum; ++i) {
            if(readyset[i].data.fd == sockfd) {
                int netfd = accept(sockfd, NULL, NULL);
                pthread_mutex_lock(&threadPool.mutex);
                enQueue(&threadPool.taskQueue, netfd);
                printf("main thread send a task\n");
                pthread_cond_signal(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
        }
    }
    return 0;
}

